package com.code2roc.fastboot.framework.redis;

import com.code2roc.fastboot.framework.config.SystemConfig;
import org.redisson.RedissonFairLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SystemConfig systemConfig;

    public boolean lock(String key, int lockExpire, boolean autoExpire) {
        key = systemConfig.getSystemTag() + "-" + key;
        RedissonFairLock rlock = (RedissonFairLock) redissonClient.getFairLock(key);
        if (rlock.isLocked()) {
            if(autoExpire){
                rlock.expire(lockExpire, TimeUnit.SECONDS);
            }
            return false;
        } else {
            if(lockExpire==0){
                rlock.lock();
            }else{
                rlock.lock(lockExpire, TimeUnit.SECONDS);
            }
            return true;
        }
    }

    //加锁-到期自动释放
    public boolean lockAutoRelease(String key,int lockExpire) {
        return lock(key,lockExpire,false);
    }

    //加锁-重复调用重置锁时间
    public boolean lockAutoReset(String key,int lockExpire) {
        return lock(key,lockExpire,true);
    }

    //加锁-看门口自动续期不释放
    public boolean lock(String key) {
        return lock(key,15,false);
    }

    public void unLock(String key) {
        key = systemConfig.getSystemTag() + "-" + key;
        RedissonFairLock rlock = (RedissonFairLock) redissonClient.getFairLock(key);
        if (rlock.isLocked()) {
            rlock.unlock();
        }
    }
}
